﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics.Year
{
    public partial class YearGateStatistics : Page
    {
        private StatisticsReportViewModel m_ViewModel;

        public YearGateStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(YearGateStatistics_Loaded);
        }

        private void YearGateStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            cmbYear.ItemsSource = FayshineManager.Instance.GetYearSource();
            cmbYear.SelectedValue = DateTime.Now.Year;

            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                SetYearGateChart();
                this.dataGrid.ItemsSource = firstHistoryPassengerFlow;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = new DateTime((int)cmbYear.SelectedValue, 1, 1);

                m_ViewModel.RefreshYearGateReport(true, dateTime);
            }
        }

        private void SetYearGateChart()
        {
            bool isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
            string subTitle = cmbInorOut.SelectedIndex == 0 ? "进客流对比" : "出客流对比";
            RenderAs renderAs = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;
            int year = (int)cmbYear.SelectedValue;

            string title1 = GetChartSubTitle();
            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = year + "年" + title1 + subTitle;
            vcChart1.Titles.Add(vcChart1Title);

            var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            List<int> monitorAreaIDs = new List<int>();
            selectAreaExt.each(s => { monitorAreaIDs.Add(s.ID); });
            bool isSingleArea = monitorAreaIDs.Count == 1 ? true : false;
            if (isSingleArea)
            {
                var topAreaGate = m_ViewModel.MonitorAreaGateExts.Where(m => m.TypeID == 1).FirstOrDefault();
                if (topAreaGate != null)
                {
                    List<int> ids = new List<int>();
                    if (topAreaGate.IsSelected)
                    {
                        ids = m_ViewModel.GetGateIDsByArea(topAreaGate.ID);
                    }
                    else
                    {
                        ids = m_ViewModel.MonitorAreaGateExts.Where(m => m.IsSelected && m.TypeID != 1).Select(mm => mm.ID).ToList();
                    }
                    ids = ids.OrderBy(i => i).ToList();
                    ids.each(id =>
                    {
                        var source = m_ViewModel.GetYearHistoryPassengerFlowByGate(isSingleArea, year, id);
                        vcChart1.Series.Add(GetDataSeries(m_ViewModel.GetGateName(id), isIn, renderAs, source));
                    });
                }
            }
            else
            {
                selectAreaExt.each(s =>
                {
                    var source = m_ViewModel.GetYearHistoryPassengerFlowByGate(isSingleArea, year, s.ID);
                    vcChart1.Series.Add(GetDataSeries(s.Name, isIn, renderAs, source));
                });
            }

        }

        private DataSeries GetDataSeries(string title, bool isIn, RenderAs randerAs, List<HistoryPassengerFlow> source)
        {
            DataSeries series = ChartHelper.GetDataSeries(randerAs,title, ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            if (isIn)
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            }
            else
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            }
            series.DataSource = source;

            return series;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
